package com.kaia.shoebox.animation;

import android.app.Activity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class ExpandCollapseAnimation extends Animation {

	private View mAnimatedView;

	private int mEndHeight;
	private int mStartVisibility;

	public ExpandCollapseAnimation(View v, int duration) {
		setDuration(duration);
		mAnimatedView = v;
		mEndHeight = mAnimatedView.getLayoutParams().height;
		mStartVisibility = mAnimatedView.getVisibility();

		if (mStartVisibility == View.GONE || mStartVisibility == View.INVISIBLE) {
			mAnimatedView.setVisibility(View.VISIBLE);
			mAnimatedView.getLayoutParams().height = 0;
		}
	}

	@Override
	protected void applyTransformation(float interpolatedTime, Transformation t) {
		super.applyTransformation(interpolatedTime, t);

		if (interpolatedTime < 1.0f) {
			if (mStartVisibility == View.GONE
					|| mStartVisibility == View.INVISIBLE) {
				mAnimatedView.getLayoutParams().height = (int) interpolatedTime
						* mEndHeight;
			} else {
				mAnimatedView.getLayoutParams().height = mEndHeight
						- (int) (interpolatedTime * mEndHeight);
			}
			mAnimatedView.requestLayout();
		} else {
			if (mStartVisibility == View.GONE
					|| mStartVisibility == View.INVISIBLE) {
				mAnimatedView.getLayoutParams().height = mEndHeight;
				mAnimatedView.requestLayout();
			} else {
				mAnimatedView.getLayoutParams().height = 0;
				mAnimatedView.setVisibility(View.GONE);
				mAnimatedView.requestLayout();
				mAnimatedView.getLayoutParams().height = mEndHeight;
			}
		}
	}

	public static void setHeightForWrapContent(Activity activity, View view) {
		DisplayMetrics metrics = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

		int width = metrics.widthPixels;

		int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
				MeasureSpec.EXACTLY);
		int widthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
				MeasureSpec.EXACTLY);

		view.measure(widthMeasureSpec, heightMeasureSpec);
		int height = view.getMeasuredHeight();
		view.getLayoutParams().height = height;
	}
}
